'''
Created on Jan 19, 2011

@author: Jonathan Herbst
'''

import time

from SQSReceiver import AWSAuthentication
from SoftSystem import Configuration

class SQSLatencyTest():
    
    def __init__(self):
        self.m_config = Configuration("config.ini")
        self.m_conn = AWSAuthentication(self.m_config.aWSAccessKey, self.m_config.aWSSecretKey).GetSQSConnection()
        self.m_queue = self.m_conn.get_queue("LatencyTest")
        if self.m_queue is None:
            self.m_queue = self.m_conn.create_queue("LatencyTest")
            
        self.m_testMessage = self.m_queue.new_message("This is a test message")
            
    def _EmptyQueue(self):
        message = True
        while message:
            message = self._RecieveAndDelete()
        
    def _RecieveAndDelete(self, recieveCycle=1):
        message = None
        while message is None and recieveCycle != 0:
            message = self.m_queue.read()
            recieveCycle -= 1
            if recieveCycle != 0:
                time.sleep(1)
        if message:
            self.m_queue.delete_message(message)
        return message
    
    def _SendMessage(self):
        self.m_queue.write(self.m_testMessage)
        
    def _TimeDataStatistics(self, timeData):
        minTime = min(timeData)
        avgTime = sum(timeData) / len(timeData)
        maxTime = max(timeData)
        
        return minTime, avgTime, maxTime
    
    def LatencyBenchmark(self, repeatTimes=10):
        
        self._EmptyQueue()
        
        timeData = []
        for i in range(repeatTimes):
            print "Iteration: %s" % i
            startTime = time.time()
            self._SendMessage()
            self._RecieveAndDelete(-1)
            endTime = time.time()
            
            print endTime - startTime
            timeData.append(endTime - startTime)
            
        timeStats = self._TimeDataStatistics(timeData)
        
        print "Min Time: %s\nAvg Time: %s\nMax Time: %s" % timeStats
        
if __name__ == "__main__":
    latencyTest = SQSLatencyTest()
    latencyTest.LatencyBenchmark()
        
        